/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.polytec.controller;

import com.polytec.beans.ClientFacade;
import com.polytec.beans.CompteFacade;
import com.polytec.controller.util.JsfUtil;
import com.polytec.controller.util.PaginationHelper;
import com.polytec.entities.Client;
import com.polytec.entities.Compte;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

/**
 *
 * @author Felix
 */
@ManagedBean(name = "inscriptionController")
@SessionScoped
public class InscriptionController implements Serializable {

    @ManagedProperty(value = "#{loginController}")
    private LoginController loginController;
    private Client current;
    private DataModel items = null;
    private int selectedItemIndex;
    @EJB
    private com.polytec.beans.ClientFacade ejbFacade;
    private Compte current1;
    @EJB
    private CompteFacade ejbFacade1;
    private PaginationHelper pagination;

    public InscriptionController() {
    }

    public Client getSelected() {
        if (current == null) {
            current = new Client();
            selectedItemIndex = -1;
        }
        return current;
    }

    public Compte getSelected1() {
        if (current1 == null) {
            current1 = new Compte();
            selectedItemIndex = -1;
        }
        return current1;
    }

    public String prepareCreate() {
        current = new Client();
        current1 = new Compte();
        selectedItemIndex = -1;
        return "Accueil.xhtml?faces-redirect=true";
    }

    public String create() {
        Compte compte = compteFacade.findByUserName(current1.getLogin());
        try {

            if (compte == null) {
                JsfUtil.addSuccessMessage("User name is available");

                if (!this.current1.getMotDePasse().equals(this.getRepassword())) {
                    JsfUtil.addErrorMessage("password doesn't match");
                    return null;

                } else {
                    if (this.current1.getMotDePasse().length() < 5) {
                        JsfUtil.addErrorMessage("passowrd too short");
                        return null;

                    } else {
                        JsfUtil.addSuccessMessage("password is successfully verified");
                        getFacade().create(current);
                        loginController.setUserName(current1.getLogin());
                        current1.setIdClient(current);
                        getFacade1().create(current1);
                        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CompteCreated"));
                        loginController.createPanier(current1);
                        return prepareCreate();

                    }
                }
            } else {
                JsfUtil.addErrorMessage("username is already used");
                return null;
            }
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public void setLoginController(LoginController loginController) {
        this.loginController = loginController;
    }

    private ClientFacade getFacade() {
        return ejbFacade;
    }

    private CompteFacade getFacade1() {
        return ejbFacade1;
    }
    @EJB
    private CompteFacade compteFacade;
//    private String userName;
//    private String password;
    private String repassword;

    public String getRepassword() {
        return repassword;
    }

    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();

                }

//                public int getItemsCount1() {
//                    return getFacade1().count();
//           
//                }
                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "Liste";
    }

//    public String prepareView() {
//        current = (Client) getItems().getRowData();
//        current1 = (Compte) getItems().getRowData();
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
//        return "/pages/View";
//    }
//     public String prepareEdit() {
//        current = (Client) getItems().getRowData();
//        current1 = (Compte) getItems().getRowData();
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
//        return "/pages/Edit";
//    }
//
//    public String update() {
//        try {
//            getFacade().edit(current);
//            getFacade1().edit(current1);
//            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CompteUpdated"));
//            return "/pages/View";
//        } catch (Exception e) {
//            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
//            return null;
//        }
//    }
//
//    public String destroy() {
//        current = (Client) getItems().getRowData();
//        current1 = (Compte) getItems().getRowData();
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
//        performDestroy();
//        recreatePagination();
//        recreateModel();
//        return "/pages/List";
//    }
//    public String destroyAndView() {
//        performDestroy();
//        recreateModel();
//        updateCurrentItem();
//        if (selectedItemIndex >= 0) {
//            return "/pages/View";
//        } else {
//            // all items were removed - go back to list
//            recreateModel();
//            return "/pages/List";
//        }
//    }
//    private void performDestroy() {
//        try {
//            getFacade().remove(current);
//            getFacade1().remove(current1);
//            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CompteDeleted"));
//        } catch (Exception e) {
//            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
//        }
//    }
//    private void updateCurrentItem() {
//        int count = getFacade().count();
//        if (selectedItemIndex >= count) {
//            // selected index cannot be bigger than number of items:
//            selectedItemIndex = count - 1;
//            // go to previous page if last page disappeared:
//            if (pagination.getPageFirstItem() >= count) {
//                pagination.previousPage();
//            }
//        }
//        if (selectedItemIndex >= 0) {
//            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
//        }
//    }
    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "Liste";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "Liste";
    }
//    public SelectItem[] getItemsAvailableSelectMany() {
//        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
//    }
//
//    public SelectItem[] getItemsAvailableSelectOne() {
//        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
//    }
//
//    @FacesConverter(forClass = Client.class)
//    public static class ClientControllerConverter implements Converter {
//
//        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
//            if (value == null || value.length() == 0) {
//                return null;
//            }
//            ClientController controller = (ClientController) facesContext.getApplication().getELResolver().
//                    getValue(facesContext.getELContext(), null, "clientController");
//            return controller.ejbFacade.find(getKey(value));
//        }
//
//        java.lang.Integer getKey(String value) {
//            java.lang.Integer key;
//            key = Integer.valueOf(value);
//            return key;
//        }
//
//        String getStringKey(java.lang.Integer value) {
//            StringBuffer sb = new StringBuffer();
//            sb.append(value);
//            return sb.toString();
//        }
//
//        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
//            if (object == null) {
//                return null;
//            }
//            if (object instanceof Client) {
//                Client o = (Client) object;
//                return getStringKey(o.getIdClient());
//            } else {
//                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Client.class.getName());
//            }
//        }
//    }
}
